<template>
  <!-- 主页 -->
  <view class="index">
    <u-navbar
      class="uNavbar"
      title="首页"
      :is-back="false"
      :background="navBgStyle"
      title-color="#fff"
      height="44"
    >
      <image class="logo" src="../../static/logo.jpg" mode="widthFix"></image>
    </u-navbar>

    <view class="content">
      <!-- 搜索栏 -->
      <u-search
        v-model="searchText"
        placeholder="日照香炉生紫烟"
        :clearabled="true"
        shape="square"
        :show-action="false"
        height="100"
        @search="toSearchPage"
      >
      </u-search>
             <!-- 吸顶的使用 -->
      <view
        :class="['tabs', tabsIsFixed ? 'tabfix' : '']"
        :style="[getTabsStyle]"
      >
        <u-tabs-swiper
          ref="uTabs"
          :list="classify"
          :name="'classifyName'"
          :current="tabscurrent"
          @change="tabsChange"
          :is-scroll="true"
          active-color="skyblue"
          height="100"
        >
        </u-tabs-swiper>
      </view>

      <!-- 分隔槽 -->
      <u-gap height="5" bg-color="skyblue"></u-gap>

      <!-- 博客轮播的容器 -->
      <view class="swiper-box">
        <swiper
          duration="300"
          :current="swiperCurrent"
          @transition="swipertransition"
          @change="swiperCurrentChange"
          @animationfinish="swiperAnimationfinish"
          :style="'height:' + swiperCurrentHeight + ';min-height:1100rpx;'"
        >
          <swiper-item
            class="swiper-item"
            v-for="item in classify"
            :key="item.id"
            :item-id="'' + item.id"
          >
            <view class="waterfall-box">
              <uni-waterfall
                v-if="item.article"
                v-model="item.article"
                ref="waterfall"
              >
                <template v-slot:left="{ leftList }">
                  <view
                    class="art-item"
                    v-for="item in leftList"
                    :key="item.blogId"
                    v-if="item.Blog"
                  >
                    <navigator
                      open-type="navigate"
                      :url="
                        '/subpages/artDetail/artDetail?artid=' + item.blogId
                      "
                    >
                      <view class="art-item-cover art-item-marbt">
                        <u-lazy-load
                          threshold="-450"
                          border-radius="10"
                          :image="item.Blog.cover"
                          img-mode="widthFix"
                          class="art-item-img"
                        >
                        </u-lazy-load>
                      </view>

                      <text class="art-item-title art-item-marbt">
                        {{ item.Blog.title }}
                      </text>
                      <view class="art-item-foot art-item-marbt">
                        <view class="art-item-author">
                          <u-avatar
                            :src="item.Blog.userAvatar"
                            size="28"
                            class="art-item-ava"
                          ></u-avatar>
                          <text>{{ item.Blog.userName }}</text>
                        </view>
                        <view class="like">
                          <u-icon
                            name="thumb-up"
                            color="skyblue"
                            size="28"
                            :label="item.Blog.like_count"
                          ></u-icon>
                        </view>
                      </view>
                    </navigator>
                  </view>
                </template>
                <template v-slot:right="{ rightList }">
                  <view
                    class="art-item"
                    v-for="item in rightList"
                    :key="item.blogId"
                    v-if="item.Blog"
                  >
                    <navigator
                      open-type="navigate"
                      :url="
                        '/subpages/artDetail/artDetail?artid=' + item.blogId
                      "
                    >
                      <view class="art-item-cover art-item-marbt">
                        <u-lazy-load
                          threshold="-450"
                          border-radius="10"
                          :image="item.Blog.cover"
                          img-mode="widthFix"
                          class="art-item-img"
                        >
                        </u-lazy-load>
                      </view>

                      <text class="art-item-title art-item-marbt">
                        {{ item.Blog.title }}
                      </text>
                      <view class="art-item-foot art-item-marbt">
                        <view class="art-item-author">
                          <u-avatar
                            :src="item.Blog.userAvatar"
                            size="28"
                            class="art-item-ava"
                          ></u-avatar>
                          <text>{{ item.Blog.userName }}</text>
                        </view>
                        <view class="like">
                          <u-icon
                            name="thumb-up"
                            color="skyblue"
                            size="28"
                            :label="item.Blog.like_count"
                          ></u-icon>
                        </view>
                      </view>
                    </navigator>
                  </view>
                </template>
              </uni-waterfall>
            </view>

            <u-empty
              text="文章空空如也~"
              mode="list"
              :show="item.article && item.article.length ? false : true"
            ></u-empty>
          </swiper-item>
        </swiper>

        <view class="loadmore-box">
          <u-loadmore
            color="skyblue"
            @loadmore="getMoreArt(10)"
            :status="loadStatus"
            :load-text="loadText"
            icon-type="flower"
          ></u-loadmore>
        </view>
      </view>
    </view>

    <u-back-top
      :scroll-top="currentPageScrollTop"
      top="100"
      :icon-style="{ color: '#fff' }"
      :custom-style="{ backgroundColor: 'skyblue' }"
    ></u-back-top>

    <!-- 底部导航栏 -->
    <u-tabbar :list="tabbarList" :mid-button="false" active-color="skyblue">
    </u-tabbar>
  </view>
</template>

<script>
import { mapState } from 'vuex';
import uniWaterfall from '@/components/uni-waterfall.vue';
import uniNavBar from '@/components/uni-nav-bar/index.vue';
export default {
  data() {
    return {
      axiosStatus: false, //	axios请求状态
      searchText: '', // 搜索栏内容
      loadStatus: 'loadmore', //	下拉加载更多状态
      loadText: {
        loadmore: '上拉/点击加载更多~',
        loading: '努力加载中~',
        nomore: '实在没有了~',
      },
      scrollcanChange: false, //	控制滚动条高度是否可以更改
      currentPageScrollTop: 0, // 页面当前滚动条高度
      tabsIsFixed: false, // 	控制tab是否吸顶
      navbarHeight: '', //  导航栏的高度
      tabsOffsetTop: '', //	tabs距离顶部高度
      swiperCurrentHeight: '0px', //	当前swiper的高度
      tabscurrent: 0, // tabs组件的current值，表示当前活动的tab选项
      swiperCurrent: 0, // swiper组件的current值，表示当前那个swiper-item是活动的
      TabCurId: '', //	tabs当前位置的分类id
      classify: [], //	分类列表
      swiperHeightList: [], // 记录每个分类下swiper的高度 和 最后滚动的高度
    };
  },

  async onLoad() {
    // 获取分类
    const classRes = await this.getClassify();
    // 获取第一个分类下的文章
    classRes && (await this.getArtFromClass(this.classify[0].id, 10, 0));
  },
  onReady() {
    // 获取NavBar的高度
    this.$u.getRect('.uNavbar', true).then((rect) => {
      // console.log(rect[0].height);
      this.navbarHeight = rect[0].height;
    });
    // 	获取tabs距离顶部的高度
    this.$u.getRect('.tabs', true).then((rect) => {
      // console.log(rect[0]);
      this.tabsOffsetTop = rect[0].top;
    });
  },
  methods: {
    // 获取分类列表
    async getClassify() {
      this.axiosStatus = false;
      try {
        let res = await this._api.getClassify();
		//console.log(res)
        if (res) {
          this.classify = res.rows;
          this.TabCurId = res.rows[0].id;
          for (let i = 0; i < res.rows.length; i++) {
            this.swiperHeightList.push({
              height: '0px',
              lastSilderHeight: 0,
            });
          }
          this.axiosStatus = true;
          return true;
        } else {
          return false;
        }
      } catch (e) {
        this.$u.toast(e.msg);
      }
    },
    //	根据分类id获取文章
    async getArtFromClass(classifyId, limit, offset) {
      // 传多一个current为了记录swiperHeightList中第n个的高度
      this.axiosStatus = true;
      let res = await this._api.getArtFromClass({
        classifyId,
        limit,
        offset,
      });
      // console.log(res);
	  // 因为要加载更多,展示出来的和没展示出来的数量进行对比 这里记录一下展示的数量
      this.classify = this.classify.map((item) => {
        if (item.id == classifyId) {
          return {
            ...item,
            articleAllCount: res.count,
            article: res.rows,
          };
        } else {
          return item;
        }
      });

      // 更改下拉加载文字提示
      if (limit > res.rows.length) {
        // 要请求的数量 大于 请求回来数组的长度 说明没有更多文章了
        this.loadStatus = 'nomore';
      } else {
        this.loadStatus = 'loadmore';
      }
      uni.$once('swiperHeightChange', (height) => {
        // 更新当前页的swiper高度
        this.swiperCurrentHeight = height;
        // 记录这个页swiper的高度
        this.swiperHeightList[this.swiperCurrent].height = height;
      });
      this.axiosStatus = false;
    },
    
	
	// tabs通知swiper切换
    tabsChange(index) {
      this.swiperCurrent = index;
    },
    // swiper-item左右移动，通知tabs的滑块跟随移动
    swipertransition(e) {
      let dx = e.detail.dx;
      this.$refs.uTabs.setDx(dx);
    },
    // 由于swiper的内部机制问题，快速切换swiper不会触发dx的连续变化，需要在结束时重置状态
    // swiper滑动结束，分别设置tabs和swiper的状态
    swiperAnimationfinish(e) {
      this.axiosStatus = false;
      let current = e.detail.current;
      // 设置tabs 的current
      this.$refs.uTabs.setFinishCurrent(current);
      //	同步tabs当前活动的Index
      this.tabscurrent = current;
      //	同步swiper当前活动的Index
      this.swiperCurrent = current;
	  
	  // 继续
      uni.pageScrollTo({
        scrollTop: this.swiperHeightList[current].lastSilderHeight,
        duration: 0,
        success: (res) => {
          this.axiosStatus = true;
          // console.log(`第${current}页上次滚动高度${this.swiperHeightList[current].lastSilderHeight}`);
        },
      });
    },
	
	
	//  这是整体的swiper改变事件
    async swiperCurrentChange(e) {
      let current = e.detail.current;
      this.axiosStatus = false;
      /* 判断分类列表中第current个，如果没有文章列表 再请求文章 
	  hasOwnProperty 判断该属性是否是this.classify[current]的自有属性,换句话说,如果没有,则没有article该值
	  */
      let hasArticle = this.classify[current].hasOwnProperty('article');

      if (!hasArticle) {
		  //走进来说明没有该值
        return this.getArtFromClass(e.detail.currentItemId, 10, 0);
      }
      // 如果已经存在文章列表 直接更改当前页swiper高度为之前记录的值
      this.swiperCurrentHeight = this.swiperHeightList[current].height;
    },

    // 请求更多文章
    async getMoreArt(limit) {
      this.axiosStatus = true;
      /* 判断当前swiper current下的artcle数量是否大道总数  没达到说明还有文章 再请求数据 */
      // 文章数量的状态 true 说明还有文章  false 为没有文章了 不同客户在不断的发表博客
      let artState =
        this.classify[this.swiperCurrent].articleAllCount >
        this.classify[this.swiperCurrent].article.length
          ? true
          : false;
      // console.log(artState);
      if (artState) {
        // 还有文章 继续请求
        // 更改loading状态
        this.loadStatus = 'loading';
		//再发请求继续拿
        let res = await this._api.getArtFromClass({
          classifyId: this.classify[this.swiperCurrent].id,
          limit: limit,
          offset: this.classify[this.swiperCurrent].article.length,
        });

        // 拼接文章列表
        this.classify[this.swiperCurrent].article = [
          ...this.classify[this.swiperCurrent].article,
          ...res.rows,
        ];

        // 更改下拉加载文字提示
        if (limit > res.rows.length) {
          // 要请求的数量 大于 请求回来数组的长度 说明没有更多文章了
          this.loadStatus = 'nomore';
        } else {
          this.loadStatus = 'loadmore';
        }

        // 更新swiper高度
        uni.$once('swiperHeightChange', (height) => {
          // 更新当前页的swiper高度
          this.swiperCurrentHeight = height;
          // 记录这个页swiper的高度
          this.swiperHeightList[this.swiperCurrent].height = height;
        });
      }
      this.axiosStatus = false;
    },
    
	// 	跳转搜索结果页
    toSearchPage() {
      this.$Router.push({
        path: '/subpages/searchPage/searchPage',
        query: { searchText: this.searchText },
      });
    },
  },
  
  //  页面监听页面滚动钩子 做吸顶效果
  onPageScroll(e) {
    // console.log(e);
    if (!this.axiosStatus) {
      // console.log(111);
      // 使tabs吸顶
      this.tabsIsFixed =
        e.scrollTop >= this.tabsOffsetTop - this.navbarHeight ? true : false;
      //  同步当前页滚动条高度

      this.currentPageScrollTop = e.scrollTop;
      // console.log(this.swiperCurrent);
      this.swiperHeightList[this.swiperCurrent].lastSilderHeight = e.scrollTop;
    }
  },
  // 页面下拉刷新 页面监听下拉动作钩子
  async onPullDownRefresh() {
	  //清空后发请求
    // console.log(this.classify);
    this.classify[this.swiperCurrent].article = [];
    // console.log(this.classify);
    this.$refs.waterfall[this.swiperCurrent].clear();
    // 获取当前swiperCurrent页面分类下的文章
    await this.getArtFromClass(this.classify[this.swiperCurrent].id, 10, 0);
   //停止当前下拉刷新
	uni.stopPullDownRefresh();
  },
  /* 触底加载钩子 */ 
  onReachBottom() {
    this.getMoreArt(10);
  },
  computed: {
    ...mapState({
      tabbarList: (state) => state.componStyle.tabbarList, // 	tabbar列表
      navBgStyle: (state) => state.componStyle.navBgStyle, //	顶部导航栏样式
    }),
    // 计算tabs的样式
    getTabsStyle() {
      if (this.tabsIsFixed) {
        return {
          top: this.navbarHeight + 'px',
        };
      } else {
        return {};
      }
    },
  },
  components: {
    'uni-waterfall': uniWaterfall,
    'uni-nav-bar': uniNavBar,
  },
};
</script>

<style lang="scss" scoped>
.index {
  .content {
    padding: 10rpx;
    .tabs {
      margin-bottom: 20rpx;
      width: 100%;
    }
    .tabfix {
      position: sticky;
      z-index: 99;
    }
    .swiper-box {
      position: relative;

      // height: 1000px;
      // background-color: $uni-bg-color-qgray;
      // background-image: linear-gradient(45deg, rgb(242,174,39), rgb(255, 255, 0));
      padding: 20rpx 10rpx;
      border-radius: 15rpx;
      .swiper-item {
        position: relative;
        .waterfall-box {
          width: 100%;
          margin-left: 10rpx;
        }
      }
      .loadmore-box {
        margin-top: 20rpx;
        width: 100%;
        background-color: #fff;
        // position: absolute;
        // bottom: 0;
      }
    }
    .art-item {
      width: 95%;
      box-shadow: rgba(242, 174, 39, 0.24) 0px 3px 8px;
      padding: 8rpx 8rpx 0;
      border: 1rpx solid $uni-border-color;
      border-radius: 16rpx;
      background-color: $uni-bg-color;
      margin-bottom: 18rpx;

      .art-item-img {
        width: 100%;
      }
      .art-item-marbt {
        margin-bottom: 11rpx;
      }
      .art-item-title {
        font-size: 30rpx;

        padding: 5rpx 8rpx 0;
        /* 需要有宽度 */
        width: 100%;
        /* 超过了就隐藏 */
        overflow: hidden;
        /* 超过了就显示省略号 */
        word-break: break-word;
        text-overflow: ellipsis;
        /* webkit内核的浏览器 */
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }
      .art-item-foot {
        /* #ifdef MP-WEIXIN */
        padding: 5rpx 8rpx 10rpx;
        /* #endif */
        /* #ifndef MP-WEIXIN */
        padding: 0 8rpx;
        /* #endif */
        display: flex;
        align-items: center;
        justify-content: space-between;
        .art-item-author {
          font-size: 28rpx;
          height: 30rpx;
          display: flex;
          align-items: center;
          .art-item-ava {
            margin-right: 8rpx;
            vertical-align: middle;
            line-height: 30rpx;
          }
        }
      }
    }
  }
}
</style>
